/*
 * @Author: silence
 * @Date: 2022-05-24 14:23:50
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2022-08-09 10:23:05
 * @Description: 获取公共数据接口
 */

import 'dart:io';
import 'package:dio/dio.dart';
import 'package:package_info/package_info.dart';
import '../../config/AppInfo.dart';
import '../../model/AppConfigEntity.dart';
import '../../model/UpdateEntity.dart';
import '../../utils/Tool/MyTools.dart';
import '../ApiUtils.dart';
import '../R.dart';
import 'dart:convert' as convert;

/// @description: 获取app全局配置
Future<R> api_app_config() async {
  R r = R();

  if (AppInfo().needCertification != null) {
    r.data = AppInfo();
    return r;
  }

  Map<String, dynamic> map = Map();
  map['format'] = 0;

  dynamic methodWait = await ApiUtils.methodAwait(
      ApiUtils.postMethod, '/api/v1.common/config',
      param: map);

  r = R.fromData(methodWait, handlerData: (map) {
    List<AppConfigEntity> resultList = [];

    for (var item in map) {
      AppConfigEntity configEntity = AppConfigEntity.fromJson(item);
      if (configEntity.name == 'PLATFORM_APP_CERTIFICATION') {
        AppInfo().needCertification = configEntity.value == '1';
      } else if (configEntity.name == 'vip_prompt_wenan') {
        AppInfo().vip_prompt_wenan = convert.jsonDecode(configEntity.value!);
      } else if (configEntity.name == 'PLATFORM_QQ_SERVICE') {
        AppInfo().qqService =
            convert.jsonDecode(configEntity.value!).toString();
      }
      resultList.add(configEntity);
    }
    return resultList;
  });

  return r;
}

/// 版本更新
Future<R> api_version() async {
  PackageInfo info = await PackageInfo.fromPlatform();

  Map<String, dynamic> map = Map();
  map['device'] = Platform.isIOS ? "2" : "1";
  map['version'] = info.version;
  map['format'] = "1";

  dynamic methodWait = await ApiUtils.methodAwait(
      ApiUtils.postMethod, '/api/v1.common/update',
      param: map, isShowLog: true);

  R r = R.fromData(methodWait, handlerData: (map) {
    UpdateEntity entity = UpdateEntity();
    if (!MyTools.mapIsEmpty(map)) {
      entity = UpdateEntity.fromJson(map);
    }
    return entity;
  });

  return r;
}

/// 上传文件
/// type: 类型 [0:文件,1:base64编码]
/// file: 文件或base64编码, base64编码仅支持图片格式
Future<R> api_upload_flie({int type = 1, required dynamic file}) async {
  Map<String, dynamic> map = Map();
  map['type'] = type;

  if (type == 0) {
    map['file'] = await MultipartFile.fromFile(file);
  } else {
    map['file'] = file;
  }

  dynamic methodWait = await ApiUtils.methodAwait(
      ApiUtils.postMethod, '/api/v1.common/upload',
      param: map, isFormData: type == 0);

  R r = R.fromData(methodWait, handlerData: (map) {
    String url = '';
    if (!MyTools.mapIsEmpty(map)) {
      url = map['url'];
    }
    return url;
  });

  return r;
}

/// 系统配置
/// group: 分组名称
/// name： 字段名称
Future<R> api_system(String group, String name) async {
  Map<String, dynamic> map = Map();
  map['group'] = group;
  map['name'] = name;

  dynamic methodWait = await ApiUtils.methodAwait(
      ApiUtils.postMethod, '/api/v1.common/system',
      param: map);

  R r = R.fromData(methodWait, handlerData: (map) {
    return map;
  });

  return r;
}

/// 获取账号注销冷静期天数
Future<int> api_logoff_calm_days() async {
  // 如果已经存在，就不需要再次获取了
  if (AppInfo().logoff_calm_days != null) {
    return AppInfo().logoff_calm_days!;
  }

  Map<String, dynamic> map = Map();
  map['group'] = 'user';
  map['name'] = 'logoff_calm_days';

  dynamic methodWait = await ApiUtils.methodAwait(
      ApiUtils.postMethod, '/api/v1.common/system',
      param: map);

  R r = R.fromData(methodWait, handlerData: (map) {
    Map result = Map();
    int days = 30; // 默认30天
    if (map != null) {
      if ((map as Map).containsKey('user')) {
        result = map['user'];
      }
    }

    if (result.containsKey('logoff_calm_days')) {
      days = int.parse(result['logoff_calm_days']);
    }

    return days;
  });

  return r.data;
}

/// 得到上传后的图片地址
Future<List<String>> getUploadPicUrLPaths(List<String> imgPaths) async {
  List<String> urlList = [];

  if (imgPaths.isNotEmpty) {
    List<Future<R>> futures = [];
    imgPaths.forEach((element) {
      if (!MyTools.stringIsEmpty(element)) {
        // 如果是网络图片地址，不需要上传，直接使用
        if (element.contains('https://') || element.contains('http://')) {
          R r = R();
          r.data = element;
          futures.add(Future.value(r));
        } else {
          futures.add(api_upload_flie(file: element, type: 0));
        }
      }
    });

    try {
      List<R> futureList = await Future.wait(futures);

      futureList.forEach((R element) {
        urlList.add(element.data);
      });

      print(urlList);
    } catch (e) {
      return Future.error('上传图片出错了');
    }
  }

  return Future.value(urlList);
}

/// 推送：绑定设备注册ID
Future<R> api_jpush_bindregid(String registrationId) async {
  Map<String, dynamic> map = Map();
  map['type'] = 1; //1:极光推送
  map['registration_id'] = registrationId;

  dynamic methodWait = await ApiUtils.methodAwait(
      ApiUtils.postMethod, '/api/v1.push/user/bindregid',
      param: map);

  R r = R.fromData(methodWait, handlerData: (map) {
    return map;
  });

  return r;
}

/// 推送：设置消息推送开关
/// is_push：消息推送 [0:否,1:是]
Future<R> api_jpush_setpush(int is_push) async {
  Map<String, dynamic> map = Map();
  map['is_push'] = is_push;

  dynamic methodWait = await ApiUtils.methodAwait(
      ApiUtils.postMethod, '/api/v1.push/user/setpush',
      param: map);

  R r = R.fromData(methodWait, handlerData: (map) {
    return map;
  });

  return r;
}
